package com.jpcc.vw.onlineRadio.activity;

import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
/*Start by menglingqiang*/
import android.util.Log;
/*End by menglingqiang*/
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.google.gson.Gson;
import com.jpcc.vw.callback.NewPayResultListener;
import com.jpcc.vw.mylibrary.PaySdk;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.AlbumDetailAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.DownloadTrackDbBean;
import com.jpcc.vw.onlineRadio.http.HttpClient;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.DetailItemClickAction;
import com.jpcc.vw.onlineRadio.model.action.DownloadTrackAction;
import com.jpcc.vw.onlineRadio.model.action.RefreshPlayingAction;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.AlbumBrowseBean;
import com.jpcc.vw.onlineRadio.model.bean.AlbumBrowseBeanNew;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.ConfirmOrderBean;
import com.jpcc.vw.onlineRadio.model.bean.PlaceOrderBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.PriceTypeInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.bean.VIPInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.XiMaLaYaOrderBean;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.PermissionReq;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;
/*Start by menglingqiang*/
import com.jpcc.vw.tracelog.TracelogInterface;
/*End by menglingqiang*/
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.lzy.okhttpserver.listener.DownloadListener;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.ThreadMode;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import rx.functions.Action0;

/**
 * 专辑详情画面
 */
public class AlbumDetailActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {


    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.layout_search)
    RelativeLayout layout_search;
    @BindView(R.id.imv_album_cover)
    CircleImageView imv_album_cover;
    @BindView(R.id.tv_album_host)
    TextView tv_album_host;
    @BindView(R.id.swipe_refrsh_tracks)
    SmartRefreshLayout swipe_refrsh_tracks;
    @BindView(R.id.recyclerview_tracks)
    RecyclerView recyclerview_tracks;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_show_empty)
    TextView tv_show_empty;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.progress_circular)
    ProgressBar progress_circular;
    @BindView(R.id.imv_new_search)
    ImageView imv_new_search;

    private IRadio radioModel;
    private AlbumDetailAdapter adapter;
    private List<Track> datas = new ArrayList<>();
    private long albumId;
    private boolean isRadio;
    private boolean is_refresh = true;
    private int page_index = 1;
    private int from = 4;
    private AlbumBrowseBean result;
    private String coverUrl;
    private String hostName;
    private boolean is_search_result = false;
    private boolean is_paied = false;
    private boolean isAuthorized = false;
    //    private boolean isVipOnly = false;
    private MaterialDialog vipDialog;

    private BroadcastReceiver vipBroadcastReceiver;
    private IntentFilter vipFilter;


    private boolean isVIPFree = false;
    private boolean isVipOnly = false;
    private boolean isSample = false;
    private boolean HidePayMark=false;


    private DownloadManager downloadManager;
    private MaterialDialog storageDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_album_detail;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        radioModel = new RadioImpl();
        downloadManager = DownloadService.getDownloadManager(this);
        downloadManager.getThreadPool().setCorePoolSize(1);
        albumId = getIntent().getLongExtra("key_album_id", -1);
        isVipOnly = getIntent().getBooleanExtra("isvipOnly", false);
//        albumId = 5203860;
        isRadio = getIntent().getBooleanExtra("key_is_radio", true);
        from = getIntent().getIntExtra("key_from", 4);
        is_search_result = getIntent().getBooleanExtra("key_search_result", false);
        is_paied = getIntent().getBooleanExtra("key_is_paied", false);
        isAuthorized = getIntent().getBooleanExtra("key_is_authorized", false);


        isVIPFree = getIntent().getBooleanExtra("isvipFree", false);
        isSample = getIntent().getBooleanExtra("isSample", false);
        HidePayMark=getIntent().getBooleanExtra("HidePayMark",false);

        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlbumDetailActivity.this.finish();
            }
        });
        imv_new_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AlbumDetailActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });
//        for (int index=0;index<10;index++){
//            AlbumDetailTrackEntity entity=new AlbumDetailTrackEntity();
//            datas.add(entity);
//        }
        adapter = new AlbumDetailAdapter(this, datas,HidePayMark);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setItemPrefetchEnabled(false);
        recyclerview_tracks.setLayoutManager(manager);
        recyclerview_tracks.setAdapter(adapter);
        swipe_refrsh_tracks.setEnableRefresh(false);
        swipe_refrsh_tracks.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                is_refresh = true;
                swipe_refrsh_tracks.setEnableLoadmore(true);
                GetAlbumBrowse();
            }
        });
        swipe_refrsh_tracks.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                is_refresh = false;
                GetAlbumBrowse();
            }
        });
        is_refresh = true;
        GetAlbumBrowse();
        vipDialog = new MaterialDialog.Builder(this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_81)).positiveText(getResources().getString(R.string.string_83)).negativeText(getResources().getString(R.string.string_82)).onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                try {
                    Intent intent = AlbumDetailActivity.this.getPackageManager().getLaunchIntentForPackage("com.jpcc.vw.personalcenter");
                    intent.putExtra("mediaType", 1);
                    intent.putExtra("jumpType", 2);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(AlbumDetailActivity.this, getResources().getString(R.string.string_84), Toast.LENGTH_SHORT).show();
                }
            }
        }).build();
        storageDialog = new MaterialDialog.Builder(this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_108)).negativeText(getResources().getString(R.string.string_32)).build();
        vipBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("VIP Status changed!");
                String vipBoughtStatus = intent.getStringExtra("payResult");
                if ("101".equals(vipBoughtStatus)) {
                    PreferenceUtils.SaveVIPStatus(true);
                }
                queryVipInfo();

            }
        };
        vipFilter = new IntentFilter("com.jpcc.vw.payment.constants.pay.result");
        this.registerReceiver(vipBroadcastReceiver, vipFilter);
        refreshVipStatus();
    }

    private void queryVipInfo() {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.QueryVIPInfo().subscribe(new CommonSubscriber<VIPInfoBean>() {
            @Override
            public void onSuccess(VIPInfoBean response) {
                if (response.getData() != null && response.getData().isVipFlag()) {
                    PreferenceUtils.SaveVIPStatus(true);
                } else {
                    PreferenceUtils.SaveVIPStatus(false);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
            }
        });
    }


    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }


    private void getPriceInfo(long trackId) {
        radioModel.GetPriceInfo(albumId).subscribe(new CommonSubscriber<PriceTypeInfoBean>() {
            @Override
            public void onSuccess(PriceTypeInfoBean response) {
                //以声音为单位进行购买
                if (response.getData().getPriceTypeDetail().get(0).getPriceType() == 1) {
                    MaterialDialog dialog = new MaterialDialog.Builder(AlbumDetailActivity.this).title(getResources().getString(R.string.string_30)).content("确认单集付费?").positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            placeOrder(false, response, trackId);
                        }
                    }).build();
                    dialog.show();
                }
                //以专辑为单位进行购买
                else {
//                    placeOrder(true, response, albumId);
                    MaterialDialog dialog = new MaterialDialog.Builder(AlbumDetailActivity.this).title(getResources().getString(R.string.string_30)).content("确认整张专辑付费?").positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            placeOrder(false, response, trackId);
                            placeOrder(true, response, albumId);
                        }
                    }).build();
                    dialog.show();
                }
            }

            @Override
            public void onFailure(BaseBean response) {

            }
        });
    }

    private void refreshVipStatus() {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.QueryVIPInfo().subscribe(new CommonSubscriber<VIPInfoBean>() {
            @Override
            public void onSuccess(VIPInfoBean response) {
                if (response.getData() != null && response.getData().isVipFlag()) {
                    PreferenceUtils.SaveVIPStatus(true);
                } else {
                    if (isVIPFree) {
//                        ToastUtils.show(R.string.string_101);
                    }
                    PreferenceUtils.SaveVIPStatus(false);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
//                ToastUtils.show(response.getStatusMessage());
            }
        });
    }


    private void placeOrder(boolean isBoughtByAlbum, PriceTypeInfoBean priceTypeInfo, long trackId) {
        String payContent = "";
        if (isBoughtByAlbum) {
            payContent = albumId + "";
        } else {
            payContent = "" + trackId;
        }
        PlaceOrderBean order = new PlaceOrderBean();
        order.setPriceType(priceTypeInfo.getData().getPriceTypeDetail().get(0).getPriceType());
        order.setPrice(priceTypeInfo.getData().getPriceTypeDetail().get(0).getDiscountedPrice() + "");
        order.setPayContent(trackId);
        order.setVin("LGVIN001000000001");
        HttpClient.PlaceOrder(new Gson().toJson(order), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ToastUtils.show("success");
                XiMaLaYaOrderBean result = new Gson().fromJson(response, XiMaLaYaOrderBean.class);
                if (result.getCode() == 0) {
//                    confirmOrder(result.getOrderNo() + "");
                    Logger.i("OrderNo-->" + result.getData().getOrderNo());
                    PaySdk.getInstance().pay(AlbumDetailActivity.this, result.getData().getOrderNo() + "", order.getPrice(), "101", new NewPayResultListener() {
                        @Override
                        public void onPaySuccess(String s) {
                            ToastUtils.show("success");

                        }

                        @Override
                        public void onPayFailed(String s) {

                        }
                    });
                } else {
                    ToastUtils.show(result.getStatusMessage());
                }
            }
        });
    }


    private void confirmOrder(String ximalayaOrderNo) {
        ConfirmOrderBean confirmOrderBean = new ConfirmOrderBean();
        confirmOrderBean.setOrderNo(ximalayaOrderNo);
        confirmOrderBean.setConfirmType(1);
        confirmOrderBean.setPayChannel(1);
        HttpClient.ConfirmOrder(new Gson().toJson(confirmOrderBean), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.show("pay success");
            }

            @Override
            public void onResponse(String response, int id) {
                XiMaLaYaOrderBean responseResult = new Gson().fromJson(response, XiMaLaYaOrderBean.class);
                ToastUtils.show("pay success");
                Logger.i(response);
            }
        });
    }

    public void onEvent(RefreshPlayingAction action) {
        adapter.notifyDataSetChanged();
    }


    public static long getFolderSize(java.io.File file) {
        long size = 0;
        java.io.File[] fileList = file.listFiles();
        if (fileList == null) {
            return 0;
        }
        for (int i = 0; i < fileList.length; i++) {

            if (fileList[i].isDirectory()) {
                size = size + getFolderSize(fileList[i]);

            } else {
                size = size + fileList[i].length();

            }
        }

        return size;
    }


    public void onEvent(DownloadTrackAction action) {
        if (TextUtils.isEmpty(action.getDir()) || TextUtils.isEmpty(action.getFileName()) || action.getTrack() == null) {
            Logger.i("not null");
            return;
        }
        Logger.i("not null");


        File downloadDir = new File(TrackUtils.getTrackDir());
//        Logger.i((getFolderSize(downloadDir) / 1024 / 1024 / 1024 / 1024) + "");
        if (getFolderSize(downloadDir) >= (2L * 1024 * 1024 * 1024 * 1024)) {
//            if (storageDialog != null && !storageDialog.isShowing()) {
//                storageDialog.show();
//            }

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Intent setAlertIntent = new Intent("com.jpcc.vw.AlbumDetailActivity");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_108));
            popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
            popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
            notificationManager.addPopup(0x0007, popup);





            return;
        }

        if (downloadManager == null) {
            downloadManager = DownloadManager.getInstance(AlbumDetailActivity.this);
        }

        try {
            DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(AlbumDetailActivity.this).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", action.getAlbumId()).and().eq("trackId",action.getTrackId()).queryForFirst();
            if(resultQuery!=null){
                ToastUtils.show(R.string.string_114);
                return;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(downloadManager.getTaskByUrl(action.getTrack().getDownloadUrl())!=null&&downloadManager.getTaskByUrl(action.getTrack().getDownloadUrl()).getState()==DownloadManager.FINISH){
            ToastUtils.show(R.string.string_29);
            return;
        }
        PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
            @Override
            public void onGranted() {
                Logger.i("onGranted()");
                Track result = action.getTrack();
                String path = action.getDir() + action.getFileName();
                ToastUtils.show(R.string.string_49);
                downloadManager.addTaskWithName(result.getDownloadUrl(), new DownloadListener() {
                    @Override
                    public void onProgress(DownloadInfo downloadInfo) {
                        //adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish(DownloadInfo downloadInfo) {
                        adapter.notifyDataSetChanged();
                        DownloadTrackDbBean info = new DownloadTrackDbBean();
                        info.setUserId(MusicApplication.GetUserId());
                        info.setAlbumId(result.getSubordinatedAlbum().getId());
                        info.setCover(result.getSubordinatedAlbum().getCoverUrlLarge());
                        info.setAlbumName(result.getSubordinatedAlbum().getAlbumTitle());
                        info.setAuthor(result.getAnnouncer().getNickname());
                        info.setTrackId(result.getId());
                        info.setTrackName(result.getTrackTitle());
                        info.setTrackUrl(TrackUtils.getTrackDir() + action.getFileName());
                        info.setTimeStamp(new Date().getTime());
                        info.setDuration(result.getDuration() * 1000);
                        info.setAlbumIntro(result.getTrackIntro());
                        try {
                            DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(AlbumDetailActivity.this).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", info.getAlbumId()).and().eq("trackId", info.getTrackId()).queryForFirst();
                            if (resultQuery != null) {
                                resultQuery.setTimeStamp(new Date().getTime());
                                DatabaseHelperOrm.getHelper(AlbumDetailActivity.this).getDownloadDao().update(resultQuery);
                            } else {
                                DatabaseHelperOrm.getHelper(AlbumDetailActivity.this).getDownloadDao().create(info);
                            }
                            ToastUtils.show(R.string.string_28);
                        } catch (SQLException e) {
//                            ToastUtils.show(R.string.string_27);
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
                        adapter.notifyDataSetChanged();
                        ToastUtils.show(R.string.string_111);
                    }

                    @Override
                    public void onAdd(DownloadInfo downloadInfo) {
                        super.onAdd(downloadInfo);
                        adapter.notifyDataSetChanged();
                    }
                }, true, action.getFileName());


//                downloadManager.addTask(TrackUtils.getTrackDir(), "" + result.getSubordinatedAlbum().getId() + result.getId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3), result.getDownloadUrl().length(),result.getDownloadUrl() , , new DownloadListener() {
//                    @Override
//                    public void onProgress(DownloadInfo downloadInfo) {
//
//                    }
//
//                    @Override
//                    public void onFinish(DownloadInfo downloadInfo) {
//                        adapter.notifyDataSetChanged();
//                    }
//
//                    @Override
//                    public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
//                        adapter.notifyDataSetChanged();
//                    }
//
//                    @Override
//                    public void onAdd(DownloadInfo downloadInfo) {
//                        super.onAdd(downloadInfo);
//                        adapter.notifyDataSetChanged();
//                    }
//                }, true);

            }

            @Override
            public void onDenied() {
                ToastUtils.show(R.string.string_37);
            }
        }).request();
    }


    private void downloadTrack() {
        RecentAlbumRadioTrackBean result = AlbumRadioAudioPlayer.get().getPlayMusic();
        if (result == null) {
            return;
        }
        if (result.canDownLoad) {
            try {
                DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(this).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", result.getAlbumId()).and().eq("trackId", result.getTrackId()).queryForFirst();
                if (resultQuery != null) {
                    ToastUtils.show(R.string.string_29);
                    resultQuery.setTimeStamp(new Date().getTime());
                    DatabaseHelperOrm.getHelper(this).getDownloadDao().update(resultQuery);
                } else {
                    String path = TrackUtils.getTrackDir() + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3);
                    File file = new File(path);
                    PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
                        @Override
                        public void onGranted() {
                            OkHttpUtils
                                    .get()
                                    .url(result.getDownloadUrl())
                                    .build().execute(new FileCallBack(TrackUtils.getTrackDir(), result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length())) {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    ToastUtils.show(getString(R.string.string_27));
                                }

                                @Override
                                public void onResponse(File response, int id) {
                                    DownloadTrackDbBean info = new DownloadTrackDbBean();
                                    info.setUserId(MusicApplication.GetUserId());
                                    info.setAlbumId(result.getAlbumId());
                                    info.setCover(result.getCover());
                                    info.setAlbumName(result.getAlbumName());
                                    info.setAuthor(result.getAuthor());
                                    info.setTrackId(result.getTrackId());
                                    info.setTrackName(result.getTrackName());
                                    info.setTrackUrl(file.getAbsolutePath());//TrackUtils.getTrackDir() + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length()));
                                    info.setTimeStamp(new Date().getTime());
                                    info.setDuration(result.getDuration());
                                    info.setAlbumIntro("");
                                    try {
                                        DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(AlbumDetailActivity.this).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", info.getAlbumId()).and().eq("trackId", info.getTrackId()).queryForFirst();
                                        if (resultQuery != null) {
                                            resultQuery.setTimeStamp(new Date().getTime());
                                            DatabaseHelperOrm.getHelper(AlbumDetailActivity.this).getDownloadDao().update(resultQuery);
                                        } else {
                                            DatabaseHelperOrm.getHelper(AlbumDetailActivity.this).getDownloadDao().create(info);
                                        }
                                        ToastUtils.show(getString(R.string.string_28));
                                    } catch (SQLException e) {
                                        ToastUtils.show(getString(R.string.string_27));
                                        e.printStackTrace();
                                    }

                                }

                                @Override
                                public void inProgress(float progress, long total, int id) {
                                }
                            });
                        }

                        @Override
                        public void onDenied() {
                            ToastUtils.show(R.string.string_41);
                        }
                    }).request();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            ToastUtils.show(R.string.string_42);
        }
    }


    private void GetAlbumBrowse() {
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), AlbumDetailActivity.this.getClass().getName(), "DEBUG", null, "GetAlbumBrowse request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetAlbumBrowse(albumId, local_page).doOnSubscribe(new Action0() {
            @Override
            public void call() {
//                showProgress();
                if(is_refresh){
                    progress_circular.setVisibility(View.VISIBLE);
                }
            }
        }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
            @Override
            public void onSuccess(AlbumBrowseBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                swipe_refrsh_tracks.finishRefresh();
                swipe_refrsh_tracks.finishLoadmore();
                if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                    tv_show_empty.setVisibility(View.GONE);
                    tv_title.setText(response.getData().getTracks().get(0).getSubordinatedAlbum().getAlbumTitle());
                    if (is_refresh) {
                        datas.clear();
                        page_index = 1;
                    }
                    is_refresh = false;
                    datas.addAll(response.getData().getTracks());
                    for (Track track : datas) {
                        track.setTrackIntro(response.getData().getAlbumIntro());
                        track.getSubordinatedAlbum().setId(albumId);
                        track.setVIPFree(isVIPFree);
                    }
                    adapter.setData(datas);
                    adapter.notifyDataSetChanged();
                    page_index++;
                } else {
                    if (is_refresh) {
                        ToastUtils.show("该专辑已被下架");
                    }
                    if (is_refresh) {
                        tv_show_empty.setVisibility(View.VISIBLE);
                    }
                    swipe_refrsh_tracks.finishLoadmore();
                    swipe_refrsh_tracks.setEnableLoadmore(false);
                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), AlbumDetailActivity.this.getClass().getName(), "DEBUG", "400", "GetAlbumBrowse onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                if (is_refresh) {
                    tv_show_empty.setVisibility(View.VISIBLE);
                }
                ToastUtils.show(response.getStatusMessage());
                swipe_refrsh_tracks.finishRefresh();
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), AlbumDetailActivity.this.getClass().getName(), "ERROR", "400", "GetAlbumBrowse onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }


    private Track Convert2Track(AlbumBrowseBeanNew.DataBean.PageDataBean input) {
        Track track = new Track();
        track.setId(input.getId());
        track.setKind("album");
        track.setTrackTitle(input.getTitle());
        track.setCoverUrlLarge(input.getImage().getUrl());
        track.setCoverUrlMiddle(input.getImage().getUrl());
        track.setCoverUrlSmall(input.getImage().getUrl());
        track.setDuration(input.getDuration());
        track.setPlayUrl32(input.getPlay_info().getPlay_32().getUrl());
        track.setPlaySize32(input.getPlay_info().getPlay_32().getSize());
        track.setCanDownload(true);
        track.setDownloadUrl(input.getPlay_info().getDownload_url().getUrl());
        track.setDownloadSize(input.getPlay_info().getDownload_url().getSize());
        SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
        subordinatedAlbum.setAlbumTitle(input.getAlbum().getTitle());
        subordinatedAlbum.setId(input.getAlbum().getId());
        subordinatedAlbum.setCoverUrlLarge(input.getAlbum().getCover().getLarge().getUrl());
        subordinatedAlbum.setCoverUrlSmall(input.getAlbum().getCover().getLarge().getUrl());
        subordinatedAlbum.setCoverUrlMiddle(input.getAlbum().getCover().getLarge().getUrl());
        track.setSubordinatedAlbum(subordinatedAlbum);
        return track;
    }

    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void initViews() {
        Glide.with(this).load(result.getData().getCoverUrlLarge()).into(imv_album_cover);
        if (result.getData().getTracks().size() > 0) {
            tv_album_host.setText(result.getData().getTracks().get(0).getAnnouncer().getNickname());
        }
        adapter.setData(result.getData().getTracks());
    }

    private void getPlayInfo(long trackId) {

        radioModel.GetPlayInfo(trackId).subscribe(new CommonSubscriber<PlayInfoBean>() {
            @Override
            public void onSuccess(PlayInfoBean response) {
                if (response.getData() != null && !TextUtils.isEmpty(response.getData().getPlayUrl24Aac())) {
                    for (int index = 0; index < datas.size(); index++) {
                        if (datas.get(index).getId() == trackId) {
                            Track track = new Track();
                            track.setPlayUrl32(response.getData().getPlayUrl24Aac());
                            List<Track> infos = new ArrayList<>();
                            infos.add(track);
                            AlbumRadioAudioPlayer.get().setOnSources(datas, 0, 4, 0);
                        }
                    }
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
            }
        });

    }


    public void onEvent(WaveAction action) {
        adapter.notifyDataSetChanged();
    }

    public void onEvent(DetailItemClickAction action) {

        Track selectedTrack = datas.get(action.getPosition());
        boolean isPaid = selectedTrack.isIs_paid();
        boolean isFree = selectedTrack.isIs_free();
        boolean isauthorized = selectedTrack.isIs_authorized();
        boolean isVipFree=selectedTrack.isVIPFree();
        Constants.LastModeFlag=false;
        if (isVIPFree) {
//            if (!isSample) {
//                if (!PreferenceUtils.GetVIPStatus()) {
//                    if (vipDialog != null && !vipDialog.isShowing()) {
//                        vipDialog.show();
//                    }
//                } else {
//                    for (Track track : datas) {
//                        track.setIs_paid(true);
//                        track.setIs_authorized(true);
//                    }
//                    AlbumRadioAudioPlayer.get().setOnSources(datas, action.getPosition(), from, -1);
//                }
//            } else {
//                for (Track track : datas) {
//                    track.setIs_paid(true);
//                    track.setIs_authorized(true);
//                }
//                AlbumRadioAudioPlayer.get().setOnSources(datas, action.getPosition(), from, -1);
//            }


            AlbumRadioAudioPlayer.get().setOnSources(datas, action.getPosition(), from, -1);
            adapter.notifyDataSetChanged();


        } else {
            AlbumRadioAudioPlayer.get().setOnSources(datas, action.getPosition(), from, -1);
            adapter.notifyDataSetChanged();
        }

//        AlbumRadioAudioPlayer.get().setOnSources(datas, action.getPosition(), from, -1);
    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        this.unregisterReceiver(vipBroadcastReceiver);
        super.onDestroy();
    }
}
